# @Time : 2024-11-29 14:18
# @Author : Fioman 
# @Phone : 13149920693
"""
生产作业日志类,主要用来负责生产作业相关日志记录,创建为单例模式
"""
import logging
import os
import threading
from datetime import datetime

import app_config
from app_config import prodDebugDir, projectName
from common.datetime_helper import get_date_only, str_to_datetime


class ProduceLogger(object):
    """
    生产日志工具类,debug()的时候,可以print和debug
    """
    _instance = None
    _lock = threading.Lock()
    _initFlag = False

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            with cls._lock:
                cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self):
        if not ProduceLogger._initFlag:
            print("ProduceLogger.__init__() 进行初始化")
            ProduceLogger._initFlag = True
            self.file_debug = self.log_init().debug

    def debug(self, message):
        """
        封装一下debug,让其可以输出到控制台,然后在输出到日志文件目录
        :param message:
        :return:
        """
        print(message)
        self.file_debug(message)

    @staticmethod
    def remove_overdue_log():
        """
        删除过期的日志,目前默认过期时间为一个月,就是会删除掉上个月份的同样名字的日志.
        :return:
        """
        try:
            for root, _, filenames in os.walk(prodDebugDir):
                for filename in filenames:
                    debugDate = filename.split('_')[0]
                    dayErrors = datetime.now() - str_to_datetime(debugDate)
                    if dayErrors.days > app_config.overdueDays:
                        os.remove(os.path.join(prodDebugDir, filename))
        except Exception as e:
            print(" error: {}".format(str(e)))

    def log_init(self):
        """
        初始化日志模块,要判断日志的目录是否存在,并且删除掉上一个月同一天的文件.
        :return:
        """
        # 删除过期日志
        self.remove_overdue_log()
        logger = logging.getLogger(__name__)
        logger.setLevel(level=logging.DEBUG)
        logger_file = f'{os.path.join(prodDebugDir, get_date_only())}_{projectName}_log.txt'
        handler_ = logging.FileHandler(logger_file, encoding="UTF-8")
        handler_.setLevel(logging.DEBUG)
        formatter_ = logging.Formatter("%(asctime)s - %(message)s")
        handler_.setFormatter(formatter_)
        logger.addHandler(handler_)
        return logger


if __name__ == '__main__':
    logger1 = ProduceLogger()
    logger2 = ProduceLogger()
    logger3 = ProduceLogger()
